package main

import (
	authpb "car_rental/auth/api/gen/v1"
	rentalpb "car_rental/rental/api/gen/v1"
	"context"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/protobuf/encoding/protojson"
	"log"
	"net/http"
)

func main() {

	logger, err := zap.NewDevelopment()

	if err != nil {
		log.Fatalf("创建zap.logger失败: %v", err)
	}

	ctx := context.Background()

	ctx, cancel := context.WithCancel(ctx)

	defer cancel()

	// 注册服务
	mux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard,
		&runtime.JSONPb{MarshalOptions: protojson.MarshalOptions{
			UseEnumNumbers: true,
			UseProtoNames:  true,
		}}))

	serverConfig := []struct {
		name         string
		addr         string
		registerFunc func(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error)
	}{
		{
			name:         "auth",
			addr:         "localhost:8081",
			registerFunc: authpb.RegisterAuthServiceHandlerFromEndpoint,
		},
		{
			name:         "trip",
			addr:         "localhost:8082",
			registerFunc: rentalpb.RegisterTripServiceHandlerFromEndpoint,
		},
	}

	for _, s := range serverConfig {

		err := s.registerFunc(
			ctx,
			mux,
			s.addr,
			[]grpc.DialOption{grpc.WithInsecure()},
		)

		if err != nil {
			logger.Sugar().Fatalf("无法注册服务: %s: %v", s.name, err)
		}

	}

	addr := ":8080"

	logger.Sugar().Infof("服务启动: %s", addr)

	logger.Sugar().Fatal(http.ListenAndServe(addr, mux))

}
